package cn.deschen.search.mysql.handlers.impl;

import cn.deschen.common.utils.SpringUtil;
import cn.deschen.search.constants.OpType;
import cn.deschen.search.index.IndexHandler;
import cn.deschen.search.index.adPlan.AdPlanIndex;
import cn.deschen.search.index.adPlan.AdPlanObject;
import cn.deschen.search.index.adUnit.AdUnitObject;
import cn.deschen.search.mysql.BinlogRowData;
import cn.deschen.search.mysql.handlers.BinlogRowDataHandler;
import cn.deschen.search.mysql.utils.SerializableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Map;

import static cn.deschen.search.constants.TableConstants.AdUnit.*;

/**
 * @Author hanbin_chen
 * @Description 推广单元处理器
 * @DateTime 2021/6/12
 * @Version V1.0.0
 */
@Component
@Slf4j
public class AdUnitHandler implements BinlogRowDataHandler {

    @Override
    public void handlerBinlogRowData(BinlogRowData rowData) {
        for (Map<String, Serializable> fieldValueMap : rowData.getRowDataList()) {
            AdUnitObject unitObject = new AdUnitObject();

            fieldValueMap.forEach((k, v) -> {
                switch (k) {
                    case COLUMN_ID:
                        unitObject.setId(SerializableUtil.parse2Long(v));
                        break;
                    case COLUMN_PLAN_ID:
                        unitObject.setPlanId(SerializableUtil.parse2Long(v));
                        break;
                    case COLUMN_UNIT_NAME:
                        unitObject.setUnitName(SerializableUtil.parse2String(v));
                        break;
                    case COLUMN_UNIT_STATUS:
                        unitObject.setUnitStatus(SerializableUtil.parse2String(v));
                        break;
                    case COLUMN_POSITION_TYPE:
                        unitObject.setPositionType(SerializableUtil.parse2String(v));
                        break;
                    case COLUMN_BUDGET:
                        unitObject.setBudget(SerializableUtil.parse2Long(v));
                        break;
                    case COLUMN_IS_DEL:
                        unitObject.setIsDel(SerializableUtil.parse2Integer(v));
                        break;
                }
            });
            AdPlanObject planObject = SpringUtil.getBean(AdPlanIndex.class).get(unitObject.getPlanId());
            if (null == planObject) {
                log.error("unit_plan is not exist; unit:{}", unitObject);
                continue;
            }
            unitObject.setPlanObject(planObject);
            IndexHandler.handlerLevel3Index(unitObject, OpType.to(rowData.getEventType()));
        }

    }
}
